import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { string } from 'zod';
import { title } from 'process';

@Injectable()
export class ErrbookService {
  constructor(private readonly prisma: PrismaService) { }

  async getErrBookList(userId: string, key, page: number = 1, size: number = 10) {
    const skip = (page - 1) * size;

    let where = {
      userId: userId,  // 过滤 userId
    }

      
    return this.prisma.user_errbook.findMany({
      where: {
        ...where,
        content: {
          chinese: {
            contains: key,
          }
        }
      },
      include: {
        content: true,
        chapter: {
          select: {
            title: true,
            course: {
              select: {
                title: true
              }
            }
          }
        },
      },
      skip,
      take: size
    });
  }

  async submitErrBook(userId: string, body: string[]) {
    await Promise.all(body.map(async (item: string) => {


      const content = await this.prisma.course_content.findUnique({
        where: {
          id: item
        }
      });

      if (!content) {
        throw new NotFoundException('内容不存在');
      }
      const errbook = await this.prisma.user_errbook.upsert({
        where: {
          userId_contentId: {
            userId: userId,
            contentId: item
          }
        },
        update: {
          errNumber: { increment: 1 }
        },
        create: {
          userId: userId,
          contentId: item,
          chapterId: content.chapterId,
          errNumber: 1,
          rightNumber: 0
        }
      });
    }));

    return { statusCode: 200, message: '错题本更新成功!' };
  }
}